const userModel=require('../../models/element-admin/user')
const { creataToken} = require('../../utils/jwt')
const jwt = require('jsonwebtoken')
class UserController{

    static async login(ctx){
        // 判断用户是否存在生成token
        let {username,password}=ctx.request.body
        // console.log(username,password,'000000')
        let userna=await userModel.findOne({username})
        if(userna){
        if(userna.password===password) {
            // 生成token
            const token = creataToken(userna)
            ctx.body = { err: 0, msg: '登录成功', data: { token }} 
        }else{
            ctx.body = { err: 1, msg: '用户名和密码不匹配', data: {}}
        }
        }else{
            ctx.body = { err: 1, msg: '该用户不存在', data: {}}
        }

    }
    static async getUserInfo(ctx){
        // 经过中间件验证
        // const u =ctx.user;
        // 不经过中间件验证
        const {token}=ctx.request.query
        // console.log(ctx.request.query)
        // console.log(token,'token')
        var decoded =jwt.verify(token, 'yyx')
        // console.log(decoded,'decoded')
        const u = decoded.data
        const info = await userModel.findOne({username: u.username})
        const roles = info.role.split(';').filter(e=>e)
        ctx.body = {
          err: 0,
          msg: 'success',
          data: {
            name: 'admin',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            introduction: '加油',
            roles,
            nike_name:info.role_name
          }
        }
      }
    }
module.exports = UserController